package com.example.demo.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.service.HusbandService;

@Controller
@RequestMapping("husband")
public class HusbandController {

	@Resource
	private HusbandService husbandService;

	@GetMapping("find_all")
	@ResponseBody
	public Object findAll() {
		return husbandService.findAll();
	}

	@PostMapping("upload")
	@ResponseBody
	public Object upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
		String contentType = file.getContentType();
		String fileName = file.getOriginalFilename();
		/*
		 * System.out.println("fileName-->" + fileName);
		 * System.out.println("getContentType-->" + contentType);
		 */
		String filePath = req.getSession().getServletContext().getRealPath("imgupload/");
		try {
			uploadFile(file.getBytes(), filePath, fileName);
		} catch (Exception e) {
			// TODO: handle exception
		}
		// 返回json
		return "uploadimg success:" + contentType;
	}

	private void uploadFile(byte[] file, String filePath, String fileName) throws IOException {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}

}
